package com.jml.代理模式.动态代理.cglib;

import java.lang.reflect.Method;


import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

public class CglibProxy implements MethodInterceptor {
	private Object targetObject;

	public Object getInstance(Object target) {
		this.targetObject = target;
		// 操作字节码 生成虚拟子类
		Enhancer enhancer = new Enhancer();
		//为目标类设置一个接口
		enhancer.setSuperclass(target.getClass());
		enhancer.setCallback(this);
		return enhancer.create();
	}

	public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
		System.out.println("开启事物");
		Object invoke = proxy.invoke(targetObject, args);
		System.out.println("提交事物");
		return invoke;
	}
}
